<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`${announcements.length > 1 ? '您有 ' + announcements.length + ' 条新公告' : '新公告'}`"
    width="650px"
    :close-on-click-modal="false"
    :show-close="false"
    class="announcement-popup-dialog"
  >
    <div class="popup-content">
      <!-- 公告列表 -->
      <div v-if="announcements.length > 0" class="announcements-list">
        <div
          v-for="(announcement, index) in announcements"
          :key="announcement.id"
          class="announcement-card"
          :class="{ 'is-active': currentIndex === index }"
        >
          <!-- 公告头部 -->
          <div class="card-header">
            <div class="header-left">
              <el-tag
                :type="utils.getLevelInfo(announcement.level).tagType"
                size="large"
                class="level-tag"
              >
                {{ announcement.levelName }}
              </el-tag>
              <el-tag
                :type="utils.getTypeInfo(announcement.type).tagType"
                size="large"
                effect="plain"
                class="type-tag"
              >
                <el-icon>
                  <component :is="utils.getTypeInfo(announcement.type).icon" />
                </el-icon>
                {{ announcement.typeName }}
              </el-tag>
              <el-tag
                v-if="announcement.isTop"
                type="danger"
                size="small"
                class="top-tag"
              >
                置顶
              </el-tag>
            </div>
            <div class="header-right">
              <span class="announcement-time">
                {{ utils.formatTime(announcement.publishTime) }}
              </span>
            </div>
          </div>

          <!-- 公告标题 -->
          <div class="card-title">
            {{ announcement.title }}
          </div>

          <!-- 公告内容 -->
          <div class="card-content">
            {{ utils.truncateContent(announcement.content, 200) }}
          </div>

          <!-- 公告操作 -->
          <div class="card-actions">
            <el-button size="small" @click="handleViewDetail(announcement)">
              查看详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleMarkAsRead(announcement)"
            >
              我知道了
            </el-button>
            <el-button
              type="info"
              size="small"
              plain
              @click="handleIgnore(announcement)"
            >
              不再提醒
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页指示器 -->
      <div v-if="announcements.length > 1" class="pagination-indicator">
        <div
          v-for="(announcement, index) in announcements"
          :key="announcement.id"
          class="indicator-dot"
          :class="{ 'is-active': currentIndex === index }"
          @click="currentIndex = index"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseAll"> 稍后处理 </el-button>
        <el-button type="primary" @click="handleMarkAllAsRead">
          全部已读
        </el-button>
      </div>
    </template>

    <!-- 公告详情对话框 -->
    <AnnouncementDetailDialog
      v-model:visible="detailDialogVisible"
      :announcement-id="selectedAnnouncementId"
      @read="handleAnnouncementRead"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Bell, Star, Tools, InfoFilled } from "@element-plus/icons-vue";
import {
  getPopupAnnouncementsApi,
  markAnnouncementAsReadApi,
  markAllAnnouncementsAsReadApi,
  ignoreAnnouncementApi,
  UserAnnouncementUtils,
  type AnnouncementInfo
} from "@/api/user-announcement";
import { useUserAuthStore } from "@/store/modules/userAuth";
import AnnouncementDetailDialog from "./AnnouncementDetailDialog.vue";

// 工具类
const utils = UserAnnouncementUtils;
const userAuthStore = useUserAuthStore();

// 状态
const announcements = ref<AnnouncementInfo[]>([]);
const currentIndex = ref(0);
const detailDialogVisible = ref(false);
const selectedAnnouncementId = ref<number>();
const internalVisible = ref(false);

// 计算属性
const dialogVisible = computed({
  get: () => internalVisible.value,
  set: value => {
    internalVisible.value = value;
    if (!value) {
      // 对话框关闭时，清空数据
      setTimeout(() => {
        announcements.value = [];
        currentIndex.value = 0;
      }, 300);
    }
  }
});

// 加载弹窗公告
const loadPopupAnnouncements = async () => {
  // 只有登录用户才加载弹窗公告
  if (!userAuthStore.isLoggedIn) {
    return;
  }

  try {
    const response = await getPopupAnnouncementsApi();
    if (response.code === 200 && response.data && response.data.length > 0) {
      announcements.value = response.data;
      currentIndex.value = 0;
      internalVisible.value = true;
    }
  } catch (error: any) {
    console.error("加载弹窗公告失败:", error);
    // 不显示错误消息，静默失败
  }
};

// 查看详情
const handleViewDetail = (announcement: AnnouncementInfo) => {
  selectedAnnouncementId.value = announcement.id;
  detailDialogVisible.value = true;
};

// 标记已读
const handleMarkAsRead = async (announcement: AnnouncementInfo) => {
  try {
    const response = await markAnnouncementAsReadApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已标记为已读");
      // 从列表中移除该公告
      announcements.value = announcements.value.filter(
        item => item.id !== announcement.id
      );
      // 如果没有公告了，关闭对话框
      if (announcements.value.length === 0) {
        dialogVisible.value = false;
      } else if (currentIndex.value >= announcements.value.length) {
        currentIndex.value = announcements.value.length - 1;
      }
    } else {
      ElMessage.error(response.message || "标记已读失败");
    }
  } catch (error: any) {
    console.error("标记已读失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 忽略公告
const handleIgnore = async (announcement: AnnouncementInfo) => {
  try {
    await ElMessageBox.confirm(
      "忽略后，该公告将不再弹窗提醒，但您仍可在消息中心查看。",
      "确认忽略",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await ignoreAnnouncementApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已忽略该公告");
      // 从列表中移除该公告
      announcements.value = announcements.value.filter(
        item => item.id !== announcement.id
      );
      // 如果没有公告了，关闭对话框
      if (announcements.value.length === 0) {
        dialogVisible.value = false;
      } else if (currentIndex.value >= announcements.value.length) {
        currentIndex.value = announcements.value.length - 1;
      }
    } else {
      ElMessage.error(response.message || "忽略公告失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("忽略公告失败:", error);
      ElMessage.error(utils.formatErrorMessage(error));
    }
  }
};

// 全部已读
const handleMarkAllAsRead = async () => {
  try {
    const response = await markAllAnnouncementsAsReadApi();
    if (response.code === 200) {
      ElMessage.success("已标记所有公告为已读");
      dialogVisible.value = false;
    } else {
      ElMessage.error(response.message || "标记全部已读失败");
    }
  } catch (error: any) {
    console.error("标记全部已读失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 关闭所有
const handleCloseAll = () => {
  dialogVisible.value = false;
};

// 公告已读回调
const handleAnnouncementRead = (id: number) => {
  // 从列表中移除该公告
  announcements.value = announcements.value.filter(item => item.id !== id);
  // 如果没有公告了，关闭对话框
  if (announcements.value.length === 0) {
    dialogVisible.value = false;
    detailDialogVisible.value = false;
  } else if (currentIndex.value >= announcements.value.length) {
    currentIndex.value = announcements.value.length - 1;
  }
};

// 监听登录状态变化
watch(
  () => userAuthStore.isLoggedIn,
  newVal => {
    if (newVal) {
      // 用户登录后，延迟1秒加载弹窗公告
      setTimeout(() => {
        loadPopupAnnouncements();
      }, 1000);
    }
  }
);

// 组件挂载时检查是否需要加载
onMounted(() => {
  if (userAuthStore.isLoggedIn) {
    // 延迟1秒加载弹窗公告
    setTimeout(() => {
      loadPopupAnnouncements();
    }, 1000);
  }
});

// 暴露刷新方法供父组件调用
defineExpose({
  refresh: loadPopupAnnouncements
});
</script>

<style scoped lang="scss">
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (width <= 768px) {
  .announcement-popup-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
    }

    :deep(.el-dialog__header) {
      padding: 16px;

      .el-dialog__title {
        font-size: 16px;
      }
    }
  }

  .popup-content {
    padding: 16px;

    .announcements-list {
      .announcement-card {
        padding: 16px;

        .card-title {
          font-size: 16px;
        }

        .card-content {
          padding: 12px;
          font-size: 13px;
        }

        .card-actions {
          gap: 8px;

          .el-button {
            flex: 1;
            min-width: auto;
          }
        }
      }
    }

    .pagination-indicator {
      gap: 6px;
      margin-top: 16px;

      .indicator-dot {
        width: 8px;
        height: 8px;

        &.is-active {
          width: 20px;
        }
      }
    }
  }

  .dialog-footer {
    gap: 8px;
    padding: 12px 16px;

    .el-button {
      flex: 1;
    }
  }
}

.announcement-popup-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin-bottom: 0;
    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #0c4a6e;
    }
  }
}

.popup-content {
  padding: 24px;

  .announcements-list {
    .announcement-card {
      display: none;
      padding: 20px;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 12px;
      transition: all 0.3s ease;

      &.is-active {
        display: block;
        animation: fade-in 0.3s ease;
      }

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        .header-left {
          display: flex;
          gap: 8px;
          align-items: center;

          .el-tag {
            display: inline-flex !important;
            gap: 4px;
            align-items: center !important;
            justify-content: center;
            height: 24px;
            padding: 0 8px !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            line-height: 1 !important;

            :deep(span) {
              display: flex;
              align-items: center;
              font-size: 13px !important;
              font-weight: 500 !important;
              line-height: 1 !important;
            }

            .el-icon {
              display: flex;
              align-items: center;
              margin: 0;
              font-size: 13px !important;
            }
          }
        }

        .header-right {
          .announcement-time {
            font-size: 13px;
            color: #909399;
          }
        }
      }

      .card-title {
        margin-bottom: 12px;
        font-size: 18px;
        font-weight: 600;
        line-height: 1.5;
        color: #0c4a6e;
      }

      .card-content {
        padding: 16px;
        margin-bottom: 20px;
        font-size: 14px;
        line-height: 1.8;
        color: #475569;
        word-break: break-word;
        white-space: pre-wrap;
        background: #f0f9ff;
        border-radius: 8px;
      }

      .card-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
      }
    }
  }

  .pagination-indicator {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 20px;

    .indicator-dot {
      width: 10px;
      height: 10px;
      cursor: pointer;
      background: #dcdfe6;
      border-radius: 50%;
      transition: all 0.3s ease;

      &:hover {
        background: #909399;
      }

      &.is-active {
        width: 24px;
        background: linear-gradient(135deg, #38bdf8 0%, #0ea5e9 100%);
        border-radius: 5px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
}
</style>
